package com.ykq.servlet;

import com.ykq.dao.BookDao;
import com.ykq.entity.Book;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(urlPatterns = "/book")
public class BookServlet extends HttpServlet {
    private BookDao bookDao = new BookDao();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //编码设置
        req.setCharacterEncoding("utf-8");
        String method = req.getParameter("method");
        if ("insert".equals(method)) {
            insert(req, resp);
        } else if ("delete".equals(method)) {
            deleteByid(req, resp);
        }else if("getById".equals(method)){
            selectById(req,resp);
        }
        else {
            //查询所有图书
            selectAll(req, resp);
        }
    }

    private void selectById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Book book= bookDao.findById(Integer.parseInt(req.getParameter("id")));
        req.setAttribute("book",book);
        req.getRequestDispatcher("/edit.jsp").forward(req,resp);
    }

    private void insert(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        double price = Double.parseDouble(req.getParameter("price"));
        String publisher = req.getParameter("publisher");
        int i = bookDao.insert(name, price, publisher);
        if(i>0){
            resp.sendRedirect("/book");
        }
    }

    private void deleteByid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接受删除的id号
        String id = req.getParameter("id");
        //调用dao方法
        int i = bookDao.delete(Integer.parseInt(id));
        if (i > 0) {//删除成功
            resp.sendRedirect("/book"); //跳转路径
        }
    }

    private void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Book> books = bookDao.selectAll();
        req.setAttribute("books", books);//保存到request中.
        req.getRequestDispatcher("/index.jsp").forward(req, resp); //必须使用转发跳转
    }
}








